package com.quan.weixin.handler;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import com.alibaba.fastjson.JSON;
import com.quan.base.common.utils.SpringContextHolder;
import com.quan.base.common.utils.XmlUtils;
import com.quan.base.common.utils.date.DateUtils;
import com.quan.weixin.WeixinConstant;
import com.quan.weixin.common.WeixinContext;
import com.quan.weixin.model.BaseMsg;
import com.quan.weixin.model.UserDetail;
import com.quan.weixin.rpc.api.WeixinApiService;
import com.quan.weixin.rpc.api.WeixinMsgService;
import com.quan.weixin.rpc.api.WeixinSubscribeUserService;
import com.quan.weixin.rpc.model.WeixinSubscribeUser;


public class WeixinRequestHandler {

	private static Logger logger = LoggerFactory.getLogger(WeixinRequestHandler.class);

	public static String processRequest(HttpServletRequest request) {
		logger.debug("收到微信请求：" + DateUtils.getDateTime());
		String respMessage = null;
		try {
			// xml请求解析
			Map<String, String> requestMap = XmlUtils.parseXml(request.getInputStream()) ;

			//将Map转换成对象
			BaseMsg baseMsg = JSON.parseObject(JSON.toJSONString(requestMap), BaseMsg.class) ;
			
			logger.debug("消息类型：" + baseMsg.getMsgType());
			logger.debug("EventKey：" + baseMsg.getEventKey());
			logger.debug("消息内容：" + baseMsg.getContent());
			logger.debug("事件类型：" + baseMsg.getEvent());
			logger.debug("地理位置纬度：" + baseMsg.getLatitude());
			logger.debug("地理位置经度：" + baseMsg.getLongitude());
			logger.debug("地理位置精度：" + baseMsg.getPrecision());
			logger.debug("消息JSON：" + baseMsg);
			
			WeixinApiService apiService = SpringContextHolder.getBean(WeixinApiService.class) ;
			WeixinSubscribeUserService subscribeUserService = SpringContextHolder.getBean(WeixinSubscribeUserService.class);
			
			WeixinMsgService weixinMsgService = SpringContextHolder.getBean(WeixinMsgService.class) ;
			
			// 文本消息
			if (baseMsg.getMsgType().equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_TEXT)) {
				Object textKeyWordHandler = weixinMsgService.textKeyWordHandler(baseMsg) ;
				if(null != textKeyWordHandler) {
					String beanToXml = XmlUtils.beanToXml(textKeyWordHandler) ;
					logger.debug("\r\n{}",beanToXml);
					return beanToXml ;
				} else {
					String beanToXml = XmlUtils.beanToXml(weixinMsgService.textMsgHandler(baseMsg, "没有找到该关键字的内容！"));
					logger.debug("\r\n{}",beanToXml);
					return beanToXml;
				}
			}
			// 图片消息
			else if (baseMsg.getMsgType().equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_IMAGE)) {
				String beanToXml = XmlUtils.beanToXml(weixinMsgService.textMsgHandler(baseMsg, "您发送的是图片消息！"));
				logger.debug("\r\n{}",beanToXml);
				return beanToXml;
			}
			// 地理位置消息
			else if (baseMsg.getMsgType().equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_LOCATION)) {
				String beanToXml = XmlUtils.beanToXml(weixinMsgService.textMsgHandler(baseMsg, "您发送的是地理位置消息！坐标（X："+requestMap.get("Location_X")+"，Y："+requestMap.get("Location_Y")+"）地址：" + requestMap.get("Label")));
				logger.debug("\r\n{}",beanToXml);
				return beanToXml;
			}
			// 链接消息
			else if (baseMsg.getMsgType().equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_LINK)) {
				String beanToXml = XmlUtils.beanToXml(weixinMsgService.textMsgHandler(baseMsg, "您发送的是链接消息！"));
				logger.debug("\r\n{}",beanToXml);
				return beanToXml;
			}
			// 音频消息
			else if (baseMsg.getMsgType().equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_VOICE)) {
				String beanToXml = XmlUtils.beanToXml(weixinMsgService.textMsgHandler(baseMsg, "您发送的是音频消息！"));
				logger.debug("\r\n{}",beanToXml);
				return beanToXml;
			}
			// 事件推送
			else if (baseMsg.getMsgType().equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_EVENT)) {
				// 自定义菜单点击事件
				if (baseMsg.getEvent().equalsIgnoreCase(WeixinConstant.EVENT_TYPE_CLICK)) {
					Object clickEventHandler = weixinMsgService.clickEventHandler(baseMsg) ;
					if(null != clickEventHandler) {
						String beanToXml = XmlUtils.beanToXml(clickEventHandler) ;
						logger.debug("\r\n{}",beanToXml);
						return beanToXml ;
					}
				}
				
				//获取地理位置
				if (baseMsg.getEvent().equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_LOCATION)) {
					logger.info("用户进入公众号每5秒获取地址位置坐标[经度：{}，纬度：{}]", baseMsg.getLongitude(), baseMsg.getLatitude());
				}
				
				// 扫码推事件
				if (baseMsg.getEvent().equalsIgnoreCase(WeixinConstant.EVENT_TYPE_SCANCODE_PUSH)) {
					return XmlUtils.beanToXml(weixinMsgService.textMsgHandler(baseMsg, "扫码推事件"));
				}

				// 扫码推事件且弹出“消息接收中”
				if (baseMsg.getEvent().equalsIgnoreCase(WeixinConstant.EVENT_TYPE_SCANCODE_WAITMSG)) {
					return XmlUtils.beanToXml(weixinMsgService.textMsgHandler(baseMsg, "扫描后返回结果给用户"));
				}
				
				// 扫描带参数二维码事件
				if (baseMsg.getEvent().equalsIgnoreCase(WeixinConstant.EVENT_TYPE_SCAN)) {
					if(StringUtils.isNotBlank(baseMsg.getEventKey()) && !baseMsg.getEventKey().equals("0")) {
						logger.debug("场景值：{}", baseMsg.getEventKey());
					}
					
					return XmlUtils.beanToXml(weixinMsgService.textMsgHandler(baseMsg, "扫描带参数二维码事件，场景值：" + baseMsg.getEventKey()));
				}

				// 订阅（关注）
				if (baseMsg.getEvent().equalsIgnoreCase(WeixinConstant.EVENT_TYPE_SUBSCRIBE)) {
					//获取关注用户信息
					UserDetail userDetail = apiService.getUserDetail(WeixinContext.getAccessToken(), baseMsg.getFromUserName()) ;
					
					WeixinSubscribeUser checkValue = subscribeUserService.checkValue("openid", userDetail.getOpenid());
					if(null == checkValue) {
						//保存关注用户信息
						WeixinSubscribeUser subscribeUser = new WeixinSubscribeUser() ;
						BeanUtils.copyProperties(userDetail, subscribeUser);
						subscribeUser.setSubscribeTime(userDetail.getSubscribe_time());
						subscribeUser.setTagidList(JSON.toJSONString(userDetail.getTagid_list()));
						subscribeUser.setHeadimgurl(userDetail.getHeadimgurl() != null ? userDetail.getHeadimgurl().replaceAll("/132", "/46") : null);
						
						subscribeUserService.insertSelective(subscribeUser);
					}
					
					logger.info("用户关注了公众号，openid:" + baseMsg.getFromUserName());
					
					String beanToXml = XmlUtils.beanToXml(weixinMsgService.subscribeHandler(baseMsg));
					logger.debug("\r\n{}",beanToXml);
					
					return beanToXml ;
				}
				// 取消订阅（取消关注）
				else if (baseMsg.getEvent().equalsIgnoreCase(WeixinConstant.EVENT_TYPE_UNSUBSCRIBE)) {
					// 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
					//subscribeUserService.deleteByOpenId(baseMsg.getFromUserName());
					logger.info("用户取消关注："+baseMsg.getFromUserName());
					
					return XmlUtils.beanToXml(weixinMsgService.textMsgHandler(baseMsg, "欢迎再次关注"));
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return respMessage;
	}

}
